package com.itheima.proxydemo;

import com.itheima.dao.pojo.Student;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

/**
 * CGLIB 动态代理
 */
public class ProxyDemo2 {
    public static void main(String[] args) {
        //调用静态方法
        getProxyCglib();
    }

    public static void getProxyCglib() {
        //创建学生类对象
        Student stu = new Student();


        Student stuProxy = (Student) Enhancer.create(
                Student.class,
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        //拿到方法名
                        String methodName = method.getName();
                        //判断是否时要增强的方法名
                        if (methodName.equals("play")) {
                            System.out.println("学生们正在操场上打篮球....");
                        }
                        //执行方法
                        Object result = method.invoke(stu, objects);
                        System.out.println("后增前.....");
                        return null;
                    }
                });
        //执行代理增强过后的方法
        stuProxy.play();
    }
}
